﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Messaging.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class TemplateController : ExtController
    {
        #region GET/POST Actions

        [HttpGet, RestoreState]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Create(Guid senderID,
            string code,
            string from,
            string to,
            string bccTo,
            string replyTo,
            string[] flags)
        {
            try
            {
                var m = Svc.ProcessOperation("CreateMessageTemplate", new
                {
                    SenderID = senderID,
                    Code = code,
                    From = from,
                    To = to,
                    BccTo = bccTo,
                    ReplyTo = replyTo,
                    Flags = flags.Merge(",")
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetMessageTemplate", new
            {
                EntityID = id,
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpPost, PersistState]
        public ActionResult Update(int id,
            Guid senderID,
            string code,
            string from,
            string to,
            string bccTo,
            string replyTo,
            string[] flags)
        {
            try
            {
                Svc.ProcessOperation("UpdateMessageTemplate", new
                {
                    EntityID = id,
                    SenderID = senderID,
                    Code = code,
                    From = from,
                    To = to,
                    BccTo = bccTo,
                    ReplyTo = replyTo,
                    Flags = flags.Merge(",")
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id)
        {
            try
            {
                Svc.ProcessOperation("DeleteMessageTemplate", new
                {
                    EntityID = id
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpPost, PersistState, ValidateInput(false)]
        public ActionResult CreateTranslation(int templateID, int languageID, string subject, string text)
        {
            try
            {
                Svc.ProcessOperation("CreateMessageTemplateTranslation", new
                {
                    HolderID = templateID,
                    LanguageID = languageID,
                    Subject = HtmlUtility.StripTags(subject),
                    Text = HtmlUtility.Encode(text)
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = templateID
            }));
        }

        [HttpPost, PersistState, ValidateInput(false)]
        public ActionResult UpdateTranslation(int id, int templateID, int languageID, string subject, string text)
        {
            try
            {
                Svc.ProcessOperation("UpdateMessageTemplateTranslation", new
                {
                    EntityID = id,
                    LanguageID = languageID,
                    Subject = HtmlUtility.StripTags(subject),
                    Text = HtmlUtility.Encode(text)
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = templateID
            }));
        }

        [HttpGet, PersistState]
        public ActionResult DeleteTranslation(int id, int templateID)
        {
            try
            {
                Svc.ProcessOperation("DeleteMessageTemplateTranslation", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = templateID
            }));
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page, int? rows, string sord, string sidx)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;
            sord = sord.Equals("desc") ? "Descending" : "Ascending";

            var m = Svc.ProcessOperation("SearchMessageTemplates", new 
            {
                Index = page * rows,
                Count = rows,
                SortBy = new[] 
                {
                    sidx
                },
                SortDir = sord
            }, new
            {
                DisclosureLevel = "Extended",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    JDM.String(i.Code),
                    JDM.String(i.From),
                    JDM.String(i.To)
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = Math.Ceiling(JDM.Double(m.TotalCount) / rows),
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        #endregion
    }
}
